import rpc from '@ohos.rpc';
import commonEvent from '@ohos.commonEvent';

const TAG = "[ServiceAbilityStub]";
const START_GAME_CODE = 101;// 业务码 开始游戏

class ServiceAbilityStub extends rpc.RemoteObject {
    constructor(des) {
        console.info(`${TAG} constructor des:${des}`);
        if (typeof des === 'string') {
            super(des)
        } else {
            return
        }
    }
    /**
     * 监听请求回调函数
     * @param code 业务请求码
     * @param data 业务数据
     * @param reply 远程服务发送的响应消息对象
     * @param option 操作是同步还是异步
     * @return 操作结果 true-操作成功 false-操作失败
     */
    onRemoteRequest(code, data, reply, option) {
        console.info(`${TAG} onRemoteRequest code:${code} ;data:${JSON.stringify(data)}`);
        // 根据业务码执行相对于的操作
        if (code === 1) {
            console.info(`${TAG} code:${code}`);
            // 进入游戏
            let gameModel = data.readInt();
            let fightId = data.readString();
            console.info(`${TAG} gameModel:${gameModel}, fightId:${fightId}`);
            this.startGameEvent(fightId, gameModel);
            // 通知FA跳转到游戏界面
            reply.writeBoolean(true);
        } else {
            console.info(`${TAG} business code err：cod:${code}`);
        }
        return true;
    }

    startGameEvent(fightId, gameModel) {
        var options = {
            code: START_GAME_CODE, //  通知开始游戏
            parameters: {
                "fightId": fightId,
                "gameModel": gameModel
            }
        }
        commonEvent.publish("startGame", options, (err) => {
            if (err.code) {
                console.error(`${TAG} [CommonEvent]PublishCallBack err = ${JSON.stringify(err)}`)
            } else {
                console.log(`${TAG} [CommonEvent] PublishCall success`)
            }
        })
    }
}

export default {
    onStart() {
        console.info(`${TAG} onStart`);
    },
    onStop() {
        console.info(`${TAG} onStop`);
    },
    onConnect(want) {
        console.log(`${TAG} onConnect, want:${JSON.stringify(want)}`);
        return new ServiceAbilityStub("service stub");
    },
    onDisconnect(want) {
        console.log(`${TAG} onDisconnect, want:${JSON.stringify(want)}`)
    },
    onCommand(want, startId) {
        console.log(`${TAG} onCommand, want:${JSON.stringify(want)},startId:${startId}`)
    }
};